/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import cn.hutool.core.util.StrUtil;
import com.lxk.oms.order.domain.req.CreateOrderReq;
import com.lxk.service.core.Result;
import com.lxk.service.ums.api.UmsServiceApi;
import com.lxk.service.ums.response.UmsUserDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ServletUtils;

import java.util.ArrayList;

/**
 * 订单上下文填充
 *
 * @author heyi
 * 2024/8/20
 */
@LiteflowComponent(value = FlowOrderNodeConst.FILL_PARAM_CREATE_ORDER)
@AllArgsConstructor
public class OrderFillContextNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);
    private final UmsServiceApi umsServiceApi;


    @Override
    public void process() throws Exception {
        CreateOrderReq params = this.getRequestData();
        log.info("下单参数:{}", params);
        OrderContext context = this.getContextBean(OrderContext.class);
        context.setTenantId(context.getTenantId());
        context.setUserRemark(params.getUserRemark());
        context.setSaveDb(params.getSaveDb());
        Long userId = params.getUserId();
        Result<UmsUserDto> userDto = umsServiceApi.queryById(userId);
        if (userDto.isFail()) {
            throw new ServiceException(userDto.getMsg());
        }
        context.setUmsUserDto(userDto.getData());
        context.setUserIp(ServletUtils.getClientIP());
        context.setMerId(params.getMerId());
        context.setOrderType(params.getOrderType());
        context.setOrderItemBoList(new ArrayList<>());
        context.setDeliveryType(params.getDeliveryType());
        // 订单名字最大为200，超过后截取前200
        context.setOrderName(StrUtil.subWithLength(params.getOrderName(), 0, 200));
        context.setCreateType(params.getCreateType());
        context.setNeedStock(params.getNeedStock());
    }

}
